<template>
  <div class="app-container">
    <es-header></es-header>
    <es-goods v-for="item in goodslist" :key="item.id" :id="item.id" :title="item.goods_name" :thumb="item.goods_img" :price="item.goods_price" :count="item.goods_count" :state="item.goods_state" @stateChange='goodsStateChange' @countchange="countchange"></es-goods>
    <es-footer @getFullChange="fullChange" :total="total" :amount="amount" :isfull="isfull"></es-footer>
  </div>
</template>

<script>
import EsHeader from './components/EsHeader/EsHeader.vue'
import EsFooter from './components/EsFooter//EsFooter.vue'
import EsGoods from './components/EsGoods/EsGoods.vue'

export default {
  name: 'MyApp',
  data() {
    return {
      goodslist: [],
      isfull: false
    }
  },
  created() {
    this.getGoodslist()
  },
  components: {
    EsHeader,
    EsFooter,
    EsGoods
  },
  methods: {
    async getGoodslist() {
     const { data: res } = await this.$http.get('/api/cart')
     if(res.status !== 200) return alert('数据获取失败！')
     console.log(res)
     this.goodslist = res.list
    },
    fullChange(state) {
     this.goodslist.forEach(x=>{
      x.goods_state = state
     })
      
    },
    goodsStateChange(obj) {
      // const item = this.goodslist.filter(x=>x.id === obj.goodsId)
      // if(item) {
      //       item[0].goods_state = obj.state
      // }

      const findResult = this.goodslist.find(x=>x.id === obj.goodsId)
      if(findResult) {
        findResult.goods_state = obj.state
      }
    },
    countchange(obj) {
       this.goodslist.find(x=>x.id === obj.id).goods_count = obj.count
    }
  },
  computed: {
    amount() {
      let a = 0
      this.goodslist.filter(x=>x.goods_state).forEach(item=>{
        a += item.goods_price*item.goods_count
      })
      return a
    },
    total() {
      let b = 0
      this.goodslist.filter(x=>x.goods_state).forEach(item=>{
        b += item.goods_count
      })
      return b
    }
  }

}
</script>

<style lang="less" scoped>
  .app-container {
    padding-top: 45px;
    padding-bottom: 50px;
  }
</style>